﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Drawing;
using Hr20.BLL;
using MethodIT.Helper;

namespace Appraisal.Web
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        private DataTable dtdetail = null;
        private DataTable dtmaster = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            btnExportExcel.Attributes.Add("onclick", "excel();");
            if (!Page.IsPostBack)
            {
                data d = new data();
                d.LoadAll();
                dtdetail = d.DefaultView.Table;
                DataColumn dc1 = dtdetail.Columns[0];
                dtdetail.Columns.Remove(dc1);

                ZB_Table_data tb_Data = new ZB_Table_data();
                tb_Data.LoadAll();
                dtmaster = tb_Data.DefaultView.Table;
                DataColumn dc2 = dtmaster.Columns[0];
                dtmaster.Columns.Remove(dc2);



                LoadData(dtmaster);

                //ExportPDF(dtmaster);
            }
        }

        private void LoadData(DataTable dt )
        {
            ZB_Table zTable = new ZB_Table();
            zTable.LoadByPrimaryKey(1);
            zTable.TableData = dt;
            //画表格
            p.Controls.Add(CreateTable(zTable));
        }

        private bool IsHeaderCell(ZB_Table zTable ,int CurrentRow,int CurrentCol)
        {
            bool bResult = false;

            if ((zTable.ColCount > CurrentCol) && (zTable.RowCount > CurrentRow))
            {
                if ((zTable.RowHead > CurrentRow) || (zTable.ColHead > CurrentCol))
                {
                    bResult = true;
                }
            }
            return bResult;
        }

        private Table CreateTable(ZB_Table zTable )
        {
            DataTable dt = zTable.TableData;

            Table tb = new Table();
            tb.Attributes.Add("style", zTable.TableStyle);
            tb.Attributes.Add("width", zTable.TableWidth.ToString() + "px");
            tb.Attributes.Add("cellpadding", "0");
            tb.Attributes.Add("cellspacing", "0");

            for (int iRow = 0; iRow < zTable.RowCount; iRow++)
            {
                //创建行
                TableRow tr = new TableRow();
                for (int iCol = 0; iCol < dt.Columns.Count; iCol++)
                {
                    TableCell tc = new TableCell();
                    //创新单元格
                    tc = CreateCell(zTable, iRow, iCol);

                    if (tc != null)
                    {
                        tr.Cells.Add(tc);
                    }
                }
                //单双行
                if (tr != null)
                {
                //    if (iRow % 2 == 0)
                //    {
                //    }
                //    else
                //    {
                //    }
                    tb.Rows.Add(tr);
                }
            }

            return tb;

        }

        private TableCell CreateCell(ZB_Table zTable, int row, int col)
        {
            DataTable dt = zTable.TableData;
            TableCell tc = null;
            
            string str = "";
            if (dt.Rows[row][col]==DBNull.Value) 
            {
                str = "NULL";
            }
            else
            {
                str = dt.Rows[row][col].ToString();
            }
            if (str.Equals("这是一个合并单元格"))
            {
                return tc;
            }
            tc = new TableCell();

            if (IsHeaderCell(zTable, row, col))
            {
                int rowspan = ClearRowData(zTable, row, col, str, 1);
                int colspan = ClearColData(zTable, row, col, str, 1);
                tc.Attributes.Add("colspan", colspan.ToString());
                tc.Attributes.Add("rowspan", rowspan.ToString());
                tc.Attributes.Add("style",zTable.RowStyle);
                //增加表头样式
            }
            else
            {
                tc.Attributes.Add("style",zTable.CellStyle);
            }

            if (str.Equals("TABLE_1"))
            {
                ZB_Table zd = new ZB_Table();
                zd.LoadByPrimaryKey(2);
                zd.TableData = dtdetail;
                tc.Controls.Add(CreateTable(zd));
            }
            else
            {
                tc.Text = str;
            }

            return tc;
        }

        private int ClearRowData(ZB_Table zTable, int row, int col, string celltext, int rowspan)
        {
            DataTable dt = zTable.TableData;

            int newrow = row + 1;
            int newcol = col ;

            if (IsHeaderCell(zTable, newrow, newcol))
            {
                if (celltext.Equals(dt.Rows[newrow][newcol].ToString()))
                {
                    dt.Rows[newrow][newcol] = "这是一个合并单元格";
                    rowspan++;
                    rowspan = ClearRowData(zTable,newrow, newcol, celltext, rowspan);
                }
            }

            return rowspan;
        }

        private int ClearColData(ZB_Table zTable, int row, int col, string celltext, int colspan)
        {
            DataTable dt = zTable.TableData;
            int newrow = row;
            int newcol = col + 1;

            if (IsHeaderCell(zTable, newrow, newcol))
            {
                if (celltext.Equals(dt.Rows[newrow][newcol].ToString()))
                {
                    dt.Rows[newrow][newcol] = "这是一个合并单元格";
                    colspan++;
                    colspan = ClearColData(zTable, newrow, newcol, celltext, colspan);
                }
            }

            return colspan;
        }

        protected void btnPDF_Click(object sender, EventArgs e)
        {
            ExportPDF(dtmaster);
        }

        private void ExportPDF(DataTable dt)
        {
            int TotalCol = dt.Columns.Count;
            int TotalRow = dt.Rows.Count;
            MemoryStream m = new MemoryStream();

            Document _pdfDocument;
            BaseFont _bfSun = BaseFont.CreateFont(@"c:\Windows\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            Table tb = (Table)p.Controls[1];

            iTextSharp.text.Font font = new iTextSharp.text.Font(_bfSun, 9, 1);
            _pdfDocument = new Document(PageSize.A4, 10, 10, 25, 25);
            //PdfWriter writer = PdfWriter.GetInstance(_pdfDocument, new FileStream(@"c:\a.pdf", FileMode.Create));
            PdfWriter writer = PdfWriter.GetInstance(_pdfDocument, m);

            _pdfDocument.Open();

            //**************************   
            //根据数据表内容创建一个PDF格式的表   
            PdfPTable table = new PdfPTable(TotalCol);
            table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY;
            table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
            //遍历原gridview的数据行   
            for (int i = 0; i < TotalRow; i++)
            {
                TableRow tr = tb.Rows[i];
                //PdfPRow pr = new PdfPRow();
                PdfPCell[] pcs = null;
                pcs = new PdfPCell[tr.Cells.Count];
                for (int j = 0; j < tr.Cells.Count ; j++)
                {
                    TableCell tc = tr.Cells[j];
                    pcs[j] = new PdfPCell(new Phrase(tc.Text, font));
                    pcs[j].Colspan = HelperDigit.ConvertToInt32(tc.Attributes["colspan"].ToString());
                    pcs[j].Rowspan = HelperDigit.ConvertToInt32(tc.Attributes["rowspan"].ToString());

                    table.AddCell(pcs[j]);
                    
                }
                PdfPRow pr = new PdfPRow(pcs);
                //table.Rows.Add(pr);
            }
            table.HeaderRows = 1;
            //在目标文档中添加转化后的表数据   

            Paragraph Title = new Paragraph("iTextSharp畫表格測試", new iTextSharp.text.Font(_bfSun, 24, 1));  
             //內容水平置中  
            Title.Alignment = 1;

            _pdfDocument.Add(Title);
            _pdfDocument.Add(new Paragraph("\n\r"));
            _pdfDocument.Add(table);

            _pdfDocument.Close();

            Response.Clear();
            Response.Buffer = false;
            Response.AddHeader("Connection", "Keep-Alive");
            Response.ContentType = "PDF";
            Response.AddHeader("Content-Disposition", "ArchiveFile;filename=" + HttpUtility.UrlEncode("PDF测试.pdf"));
            //Response.AddHeader("Content-Length", m.Length.ToString());

            //byte[] buffer = new byte[m.Length];
            //int leng = m.Read(buffer, 0, (int)m.Length);
            //Response.BinaryWrite(buffer);
            Response.AddHeader("Content-Disposition", "attachment;FileName=PDF测试.pdf");
            Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
            Response.End();
            //HttpContext.Current.Response.OutputStream.Flush();
            //HttpContext.Current.Response.OutputStream.Close();
        }
    }
}
